using UnityEngine;
using System.Collections;

public class TileMap 
{
    //the base texture that the tiles will be pulled from
    //***IMPORTANT***
    //If this texture was added as an asset to the project like it is in the demo project,
    //you MUST switch the Texture Type to Advance in the Texture Importer, then turn on
    //read/write enabled.  If you don't do this Unity will throw an error when you try to
    //use GetPixels.
    //***IMPORTANT PART 2***
    //In the advanced settings, unless your tilemap is a power of 2 (128,256,512,ect) you MUST change
    //the Non Power of 2 property to none.  Default behavior is to scale the image to the
    //nearest power of 2.
    private Texture2D baseTileMap;
    //tile size.  assumed tiles are square
    public int tileSize;
    //the array of tiles.  Index 0 is in upper left
    public Texture2D[] tiles;
    //what is the width in tiles of the original tile map.
    public int width;

    public int counter = 0;
    public bool done = false;


    /// <summary>
    /// Takes a traditional tilemap and breaks it into individual tiles
    /// </summary>
    /// <param name="baseTiles">must be square i.e. 512x512</param>
    /// <param name="tileSize">assumes square tiles</param>
    public TileMap(Texture2D baseTiles,int tileSize)
    {
        this.tileSize = tileSize;
        this.baseTileMap = baseTiles;
        int targetWidth = baseTiles.width / tileSize;
        this.width = targetWidth;
        tiles = new Texture2D[targetWidth * targetWidth];

        //used to hold the color data for each tile
        Color[] tileColor;
        //need to use a seperate variable to track where in the tiles[] array to
        //place tile info.  otherwise it gets reversed due to row counting down
        //instead of up
        int targetIndex = 0;

        //for (int row = 0; row < targetWidth; row++)
        for(int row = targetWidth - 1; row >=0; row--) //I want 0 in the upper left.  I just do.  Don't judge me.
        {
            for (int col = 0; col < targetWidth; col++)
            {
                //find the x,y of the source tile map
                int sourceX = col * tileSize;
                int sourceY = row * tileSize;
                //grab that chunk of color data
                tileColor = baseTiles.GetPixels(sourceX, sourceY, tileSize, tileSize);
                //create the tile and assign the color data
                tiles[targetIndex] = new Texture2D(tileSize, tileSize, TextureFormat.ARGB32, false);
                tiles[targetIndex].SetPixels(tileColor);
                //***ALWAYS*** remember to call Apply() when altering color data
                tiles[targetIndex].Apply();
                targetIndex++;
                counter = targetIndex;
            }
        }//end row for
        done = true;
    }//end TileMap()
	
}
